<?php

namespace app\api\controller;

use app\admin\model\Moder;
use app\admin\model\OrderProducts;
use app\admin\model\Wechat;
use app\common\controller\Api;
use fast\Random;
use think\Config;
use think\Db;
use think\Loader;

// 引入 extend/wechat-sdk/wechat.class.php
Loader::import('wechatpay.WxPay', EXTEND_PATH, '.Api.php');
Loader::import('wechatpay.WxPay', EXTEND_PATH, '.Config.php');
Loader::import('wechatpay.WxPay', EXTEND_PATH, '.Data.php');
// 引入 extend/qrcode.php
//Loader::import('wechatpay',EXTEND_PATH, 'notify.php');
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页，
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * 获取登录信息
     */
    public function getLoginInfo(){
        $param = $this->request->post();
        if (empty($param['code'])){
            $this->success('code不能为空');
        }
        $res = $this->getWeChatUserInfos($param['code']);
        $this->success('请求成功',$res);
    }

    /**
     * 获取微信信息
     */
    public function getWeChatUserInfos($code){
        $wechatConfig = Config::get('weChatPayConfig');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$wechatConfig['AppID']."&secret=".$wechatConfig['AppSecret']."&js_code=".$code."&grant_type=authorization_code";
        $json = file_get_contents($url);
        $arr = json_decode($json,true);
//        print_r($arr);die;
//        $token = $arr['access_token'];
//        $openid = $arr['openid'];
//        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openid ";
//        $json = file_get_contents($url);//获取微信用户基本信息
//        $arr = json_decode($json,true);
        return $arr;
    }

    /**
     * 统一下单
     */
    public function unifiedOrder(){
        $wechatConfig = Config::get('weChatPayConfig');
        $param = $this->request->post();
        //商户订单号
        $orderNO = date('YmdHis').Random::numeric();
        //价格(以分为单位)
        $totalPrice = 0;
        //商品信息
        if (empty($param['orderInfo'])){
            $this->success('商品信息为空');
        }
        if (empty($param['openid'])){
            $this->success('openid为空');
        }
        foreach ($param['orderInfo'] as $ok => $ov){
            $totalPrice += $ov['price'] * $ov['num'];
        }
        //商品或支付单简要描述
        $describe = empty($param['describe'])?'无':$param['describe'];

        $openid = $param['openid'];

        //统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($describe);
        $input->SetAttach("");
        $input->SetOut_trade_no($orderNO);
        $input->SetTotal_fee($totalPrice);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("");
        $input->SetNotify_url($wechatConfig['NotifyUrl']);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $config = new \WxPayConfig();
        $order = \WxPayApi::unifiedOrder($config, $input);

        //再次签名
        //  提交JSAPI输入对象
        $jsApiPayData = new \WxPayJsApiPay();
        //设置appid
        $jsApiPayData->SetAppid($wechatConfig['AppID']);
        //timeStamp
        $jsApiPayData->SetTimeStamp((string)time());
        //随机串
        $randStr = md5(time().mt_rand(0,1000));
        $jsApiPayData->SetNonceStr($randStr);
        //数据报
        $jsApiPayData->SetPackage('prepay_id='.$order['prepay_id']);
        //类型
        $jsApiPayData->SetSignType($wechatConfig['SignType']);
        //生成签名
        $sign  = $jsApiPayData->MakeSign($config);
        //获得签名数组
        $signData = $jsApiPayData->GetValues();
        //增加字段paySign
        $signData['paySign']=$sign;
        //删除signData中的app_Id字段
        unset($signData['appId']);
        //回传商户订单号
        $signData['out_trade_no'] = $orderNO;

        $this->success('请求成功',$signData);
    }


    /**
     * 支付回调
     */
    public function notify(){
        $xml = file_get_contents("php://input");

        if(!$xml){
            return;
        }
        //将XML转为array
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        logging(__FILE__,$data);

        $moder = new Moder();
        $id = $moder->where(['transaction_id'=>$data['transaction_id']])->value('id');
        if ($id){
            $data['id'] = $id;
        }
        $moder->allowField(true)->saveAll([$data]);


        $returnXml = "<xml>
                          <return_code><![CDATA[SUCCESS]]></return_code>
                          <return_msg><![CDATA[OK]]></return_msg>
                      </xml>";
        return $returnXml;




    }

    /**
     * 检查是否有微信用户昵称，头像信息
     */
    public function checkLog(){
        $param = $this->request->post();
        $openid = empty($param['openid'])?'':$param['openid'];
        $res = Db::name('wechat')->where(['openid'=>$openid])->field('nickname,openid,avatarUrl')->find();
        $this->success('',$res);
    }

    /**
     * 存储微信用户
     */
    public function saveWechat(){
        $param = $this->request->post();
        $openid = empty($param['openid'])?'':$param['openid'];
        if (!$openid){
            return;
        }
        $id = Db::name('wechat')->where(['openid'=>$openid])->value('id');
        $param['time'] = date('Y-m-d H:i:s');
        $wechatMode = new Wechat();
        if ($id){
            $wechatMode->where('id',$id)->update($param);
        }else{
            $wechatMode->where('id',$id)->insert($param);
        }
    }

    /**
     * 存储订单号对应的商品信息
     */
    public function saveOrderProducts(){
        $param = $this->request->post();
        $param['products'] = json_encode($param['products']);
        (new OrderProducts())->allowField(true)->saveAll([$param]);
    }

    public function xx(){
        $ip = $this->request->ip();
        $this->success('',$_SERVER);
    }


}
